<template>
  <div class="production-order-container">
    <div class="header">
      <!-- 左侧：系统名称 -->
      <div class="system-name">智能调度系统</div>

      <!-- 中间：当前时间 -->
      <div class="current-time">{{ currentTime }}</div>

      <!-- 右侧：用户信息和退出按钮 -->
      <div class="user-info">
        <span class="welcome-text">你好，{{ userName }}</span>
        <span class="user-id">({{ userId }})</span>
        <el-button class="logout-btn" type="text" @click="logout">退出登录</el-button>
      </div>
    </div>
    <div class="content">
      <!-- 搜索区 -->
      <div class="search-area">
        <div class="search-row">
          <span class="search-label">订单编码：</span>
          <el-input v-model="orderCode" class="search-input" placeholder="请输入" style="width: 20%;" />
          <span class="search-label">车辆号：</span>
          <el-input v-model="carNumber" class="search-input" placeholder="请输入" style="width: 20%;" />
          <el-button class="search-btn" type="primary" @click="handleSearch">查询</el-button>
          <el-button class="reset-btn" @click="handleReset">重置</el-button>
        </div>
      </div>

      <!-- 数据展示区 -->
      <div class="data-container">
        <div v-if="loading" class="loading-container">
          <el-icon class="is-loading">
            <Loading />
          </el-icon>
          加载中...
        </div>

        <div v-else-if="orderList.length === 0" class="empty-container">
          暂无数据
        </div>

        <div v-else class="order-list">
          <div v-for="(order, index) in orderList" :key="index" :class="{ 'selected-order': selectedOrderId === order.orderId }"
            class="order-item" @click="handleOrderClick(order.orderId)">
            <div class="order-header">
              <span :class="getStatusClass(order.status)" class="order-status">
                {{ getStatusText(order.status) }}
              </span>
            </div>
            <div class="order-content">
              <el-row :gutter="20">
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">订单编码：<span>{{ order.processName
                }}</span></el-col>
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">车辆号：<span>{{ order.carNumber
                }}</span></el-col>
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">工单编码：<span>{{ order.processOrderCode
                }}</span></el-col>
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">工位：<span>{{ order.processName
                }}</span></el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">工序号：<span>{{ order.processOrderCode
                }}</span></el-col>
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">工序名称：<span>{{ order.processName
                }}</span></el-col>
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">计划开始时间：<span>{{ order.carNumber
                }}</span></el-col>
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">计划结束时间：<span>{{ order.carNumber
                }}</span></el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">实际开始时间：<span>{{ order.processName
                }}</span></el-col>
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">实际结束时间：<span>{{ order.processName
                }}</span></el-col>
                <el-col :lg="6" :md="6" :offset="0" :sm="6" :xl="6" :xs="6">作业人：<span>{{ order.processName
                }}</span></el-col>
              </el-row>
            </div>
            <div class="order-footer">
              <template v-if="order.status === OrderStatus.UNSTARTED">
                <el-button type="primary" @click.stop="handleStartWork(order)">
                  开工
                </el-button>
              </template>

              <template v-else-if="order.status === OrderStatus.STARTED">
                <el-button type="warning" @click.stop="handleExceptionReport(order)">
                  异常上报
                </el-button>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ElMessageBoxOptions } from "element-plus/es/components/message-box/src/message-box.type";
import { useUserStore } from '@/store/modules/user';
import { processWorkOrderList } from '@/api/processWorkOrder/types';

const router = useRouter()
const userStore = useUserStore();

enum OrderStatus {
  UNSTARTED = 'unstarted',
  STARTED = 'started',
  WAITING = 'waiting',
  COMPLETED = 'completed'
}

const userName = ref('张三')
const userId = ref('11324')

// 当前时间
const currentTime = ref('')
let timer: any = null

// 更新时间函数
const updateTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekday = weekdays[now.getDay()]
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  currentTime.value = `${year}年${month}月${day}日 ${weekday} ${hours}:${minutes}:${seconds}`
}
// 搜索相关
const orderCode = ref('')
const carNumber = ref('')
const loading = ref(false)
const selectedOrderId = ref<string | null>(null)

// 订单数据
const orderList = ref<processWorkOrderList[]>([
  {
    orderId: '20240218001',
    carNumber: '999382',
    processOrderCode: '20240218001-10',
    processName: '表面清理',
    workstation: '83320301-喷砂间',
    planDate: '2024-02-14',
    status: OrderStatus.STARTED
  },
  {
    orderId: '20240218002',
    carNumber: '999382',
    processOrderCode: '20240218001-10',
    processName: '表面清理',
    workstation: '83320301-烘干间',
    planDate: '2024-02-14',
    status: OrderStatus.WAITING
  },
  {
    orderId: '20240218003',
    carNumber: '999382',
    processOrderCode: '20240218001-10',
    processName: '喷砂处理',
    workstation: '喷砂处理',
    planDate: '',
    status: OrderStatus.UNSTARTED
  }
])

// 状态文本映射
const statusTextMap = {
  unstarted: '未开工',
  started: '已开工',
  waiting: '完工待检',
  completed: '完工'
}

// 状态类名映射
const statusClassMap = {
  unstarted: 'status-unstarted',
  started: 'status-started',
  waiting: 'status-waiting',
  completed: 'status-completed'
}

// 获取状态文本
const getStatusText = (status: string) => {
  return statusTextMap[status as keyof typeof statusTextMap] || status
}

// 获取状态类名
const getStatusClass = (status: string) => {
  return statusClassMap[status as keyof typeof statusClassMap] || ''
}


const logout = async () => {
  await ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  } as ElMessageBoxOptions);
  userStore.logout().then(() => {
    router.replace({
      path: '/login',
      // query: {
      //   redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
      // }
    });
  });
}

// 处理订单点击
const handleOrderClick = (orderId: string) => {
  selectedOrderId.value = selectedOrderId.value === orderId ? null : orderId
}

// 处理搜索
const handleSearch = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索完成')
  }, 800)
}
// 处理重置
const handleReset = () => {
  orderCode.value = ''
  carNumber.value = ''
}

// 处理开工操作
const handleStartWork = (order: any) => {
  console.log('开工操作:', order)
  // 这里可以调用API更新工单状态
  ElMessage.success(`工单 ${order.orderId} 已开工`)
  // 更新本地状态（实际开发中应该从API获取最新状态）
  order.status = 'started'
}

// 处理异常上报
const handleExceptionReport = (order: any) => {
  console.log('上报异常:', order)
  router.push({
    path: '/exception-report',
    query: {
      orderId: order.orderId,
      processName: order.processName
    }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  // fetchOrderData()
  updateTime()
  timer = setInterval(updateTime, 1000)
})

// 清除定时器
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style lang="scss" scoped>
.production-order-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  // max-width: 800px;
  // margin: 0 auto;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background-color: #566baa;
    color: white;
    font-size: 16px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .system-name {
      font-size: 20px;
      font-weight: bold;
      flex: 1;
    }

    .current-time {
      flex: 1;
      text-align: center;
    }

    .user-info {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 10px;

      .welcome-text {
        margin-right: 5px;
      }

      .user-id {
        opacity: 0.8;
        font-size: 14px;
      }

      .logout-btn {
        color: white;
        margin-left: 10px;

        &:hover {
          color: #ffeb3b;
        }
      }
    }
  }

  .content {
    padding: 15px;
    background-color: #1d2442;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .search-area {
    background-color: #566baa;
    padding: 15px;

    .search-row {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px;

      .search-label {
        font-size: 14px;
        color: #fff;
      }

      .search-input {
        width: 150px;
      }

      .search-btn,
      .reset-btn {
        margin-left: 10px;
      }
    }
  }

  .data-container {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
    background-color: #566baa;


    .loading-container,
    .empty-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100px;
      color: #999;
    }

    .order-list {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .order-item {
        background-color: white;
        // border-radius: 8px;
        padding: 15px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        position: relative;

        &.selected-order {
          background-color: #CAF982 !important;
          transition: background-color 0.3s ease;
        }

        &:hover {
          cursor: pointer;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
        }

        .order-header {
          position: absolute;
          right: 15px;
          top: 15px;

          .order-status {
            font-size: 12px;
            padding: 3px 8px;

            &.status-unstarted {
              background-color: #f0f0f0;
              color: #666;
            }

            &.status-started {
              background-color: #e6f7ff;
              color: #1890ff;
            }

            &.status-waiting {
              background-color: #fff7e6;
              color: #fa8c16;
            }

            &.status-completed {
              background-color: #f6ffed;
              color: #52c41a;
            }
          }
        }

        .order-content {
          display: flex;
          flex-direction: column;
          gap: 15px;
          font-size: 14px;

          .order-row {
            display: flex;

            span:first-child {
              color: #666;
              min-width: 80px;
            }

            span:last-child {
              color: #333;
            }
          }
        }

        .order-footer {
          position: absolute;
          right: 15px;
          bottom: 15px;
        }
      }
    }
  }
}
</style>
